from app import app
from flask import Flask, render_template, request, jsonify, make_response, session
from flask_restful import inputs
from app.libs.Codes import TextCode
from app.libs.Verifys import passWord
from app.models import *
from app.admin.admin_login import admin_require
from app.libs.QINIU import delect as QiniuDel, pfop_m3u8
from sqlalchemy import or_
import time
import hashlib
import random
from app.setting import *
from html import unescape
import re
from sqlalchemy.orm.attributes import flag_modified


def admin_cookis_md5(username, password):
    m = hashlib.md5()
    data = username + password + str(time.time()) + "skuhas>><.s55" + str(random.randint(10000, 99999))
    data = data.encode(encoding='utf-8')
    m.update(data)
    str_md5 = m.hexdigest()
    return str_md5


def html_to_plain_text(html):
    text = re.sub('<head.*?>.*?</head>', '', html, flags=re.M | re.S | re.I)
    text = re.sub('<a\s.*?>', ' HYPERLINK ', text, flags=re.M | re.S | re.I)
    text = re.sub('<.*?>', '', text, flags=re.M | re.S)
    text = re.sub(r'(\s*\n)+', '\n', text, flags=re.M | re.S)
    return unescape(text).replace('\n', '\n\n')


# 后台验证码
@app.route('/pdd/admin/code', methods=["post", "get"])
def admin_code():
    if request.method == "GET":
        code = TextCode(6)
        session["ad_session_code"] = {"code": code[0], "time": int(time.time() + 60)}
        return jsonify(code=0, msg="获取成功", data=code[1])
    elif request.method == "POST":
        return session.get('ad_session_code') or "None"


# 后台登录
@app.route('/pdd/admin/login', methods=["post"])
def admin_login():
    username = request.form.get("username", type=str)
    password = request.form.get("password", type=str)
    code = request.form.get("code", type=str)
    vcode = session.get('ad_session_code').get("code")
    vtime = session.get('ad_session_code').get("time")
    if vcode is None or vtime is None:
        return jsonify(code=-1, msg="验证码错误")
    try:
        if code.upper() != vcode:
            return jsonify(code=-1, msg="验证码错误")
        if vtime < int(time.time()):
            return jsonify(code=-1, msg="验证码失效单击刷新")

    except:
        return jsonify(code=-1, msg="验证码错误")

    if username is None:
        return jsonify(code=-1, msg="用户名错误")
    if password is None:
        return jsonify(code=-1, msg="密码错误")

    v = passWord(password, 25, 8)

    if v == 2:
        return jsonify(code=-1, msg="密码不能低于8位")
    if v == 3:
        return jsonify(code=-1, msg="密码长度高于25位")
    if v == 4:
        return jsonify(code=-1, msg="请输入的密码为数字字母加字符的任意组合")

    admin = Admin.query.filter(Admin.username == username).first()
    if not admin:
        return jsonify(code=-1, msg="用户名错误")

    if password == admin.password:
        cookies = admin_cookis_md5(username, password)
        cobj = Admin_Cookies(cookies=cookies,
                             endTime=(datetime.datetime.now() + app.config['PEMEMBER_COOKIE_DURATION']).timetuple(),
                             admin_id=admin.id)
        try:
            db.session.add(cobj)
            db.session.commit()
            resp = make_response(jsonify({
                'code': 0,
                'msg': '登陆成功'
            }))

            resp.set_cookie("ad_uuid", cobj.cookies)
            return resp
        except:
            db.session.rollback()
            return jsonify(code=-1, msg="服务器出错,请稍后重试,或联系客服")

    else:
        return jsonify(code=-1, msg="密码错误")


# 获取个人信息
@app.route('/pdd/admin/info', methods=["get"])
@admin_require
def admin_info(aid):
    return jsonify(code=0, msg="获取成功", data={
        "username": aid.username,
        "userPhoto": API_SET.get("QINIU").get("qiniu_url") + aid.userPhoto if aid.userPhoto else None,
        "phone": aid.phone,
        "sex": "男" if aid.sex == 1 else "女",
        "name": aid.name,
        "address": aid.address,
        "birthdate": str(aid.birthdate),
        "jobName": aid.job.jobName
    })


# 退出后台账号
@app.route('/pdd/admin/quit', methods=["post", "get"])
def admin_quit():
    aid = request.cookies.get("ad_uuid")

    if aid is None:
        resp = make_response(jsonify({
            'code': -101,
            'msg': '你还没有登录！'
        }))
        resp.delete_cookie("ad_uuid")
        return resp

    acookie = Admin_Cookies.query.filter_by(cookies=aid).first()
    if acookie:
        try:
            db.session.delete(acookie)
            db.session.commit()
            resp = make_response(jsonify({
                'code': 0,
                'msg': '退出成功！'
            }))
            resp.delete_cookie("ad_uuid")
            return resp
        except:
            db.session.rollback()
            resp = make_response(jsonify({
                'code': -1,
                'msg': '退出失败！'
            }))
            return resp

    else:
        resp = make_response(jsonify({
            'code': 0,
            'msg': '退出成功！'
        }))
        resp.delete_cookie("ad_uuid")
        return resp


# 获取后台日志
@app.route('/pdd/admin/operate', methods=["post", "get"])
@admin_require
def admin_operate(aid):
    '''
    :param page:页码
    :param up:1：添加，2：修改 3：删除 4：上线下
    :param startTime:开始时间
    :param endTime:结束时间
    :param pageSize:每页大小
    :return:
    '''
    page = request.args.get('page', default=0, type=int)
    up = request.args.get("up", type=int)
    startTime = request.args.get('startTime', type=str)
    endTime = request.args.get('endTime', type=str)
    pageSize = request.args.get('pageSize', default=10, type=int)
    sql = list()
    if up in [1, 2, 3, 4]:
        sql.append(Admin_operate_log.up == up)
    if startTime and endTime:
        endTime = datetime.datetime.strptime(endTime, '%Y-%m-%d') + datetime.timedelta(days=1)

        sql.append(Admin_operate_log.createtime.between(startTime, endTime))

    pager = Admin_operate_log.query.filter(*sql).order_by(Admin_operate_log.createtime.desc()).paginate(page,
                                                                                                        per_page=pageSize,
                                                                                                        error_out=False)

    data = []
    for i in pager.items:
        data.append({
            "username": aid.name,
            "userPhoto": API_SET.get("QINIU").get("qiniu_url") + aid.userPhoto if aid.userPhoto else None,
            "func": i.func,
            "up": "添加" if i.up == 1 else "修改" if i.up == 2 else "删除" if i.up == 3 else "上下线",
            "comment": i.comment,
            "createtime": str(i.createtime)
        })
    return jsonify(code=0, msg="成功",
                   page=pager.page,
                   total=pager.total,
                   pages=pager.pages,
                   rows=data,
                   )


'''
轮播图处理
'''


# 添加轮播图
@app.route('/pdd/admin/slideshow/add', methods=["post"])
@admin_require
def admin_slideshow_add(aid):
    '''
    :param name: 轮播名称
    :param rank: 图片排序
    :param imgName:图片名称
    :param href:跳转链接
    :param zone:发布空间 1：首页 2：个人中心 3：功能页
    :return:
    '''
    if not aid.job.imgText:
        return jsonify(code=-103, msg="没有权限")

    name = request.form.get("name", type=str)
    rank = request.form.get("rank", type=int, default=1)
    imgName = request.form.get("imgName", type=str)
    href = request.form.get("href", type=str)
    zone = request.form.get("zone", type=int)

    if name is None:
        return jsonify(code=-1, msg="轮播名称不能为空")
    if rank is None:
        return jsonify(code=-1, msg="轮播排序不能为空")
    if imgName is None:
        return jsonify(code=-1, msg="上传图片不能为空")
    if not zone in [1, 2, 3]:
        return jsonify(code=-1, msg="请选择上传到哪个位置")

    newView = ViewPager(zone=zone, name=name, imgName=imgName, href=href, rank=rank, status=True)

    # 添加日志
    operate_comment = []
    operate_comment.append({"name": "轮播名称", "content": name})
    operate_comment.append({"name": "轮播排序", "content": rank})
    operate_comment.append({"name": "图片名称", "content": imgName})
    operate_comment.append({"name": "发布空间", "content": "首页" if zone == 1 else "个人中心" if zone == 2 else "功能页"})
    operate_comment.append({"name": "跳转链接", "content": href})
    log = Admin_operate_log(func="轮播图", up=1, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(newView)
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="上传成功", data={
            "id": newView.id,
            "name": newView.name,
            "imgPath": API_SET.get("QINIU").get("qiniu_url") + newView.imgName,
            "href": newView.href,
            "rank": newView.rank,
            "imgName": newView.imgName,
            "status": newView.status,
            "createtime": str(newView.createtime),
            "updateTime": str(newView.updateTime),
            "zone": newView.zone
        })
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="添加失败，服务器出错了，请稍后重试")


# 编辑轮播图
@app.route('/pdd/admin/slideshow/edit', methods=["post"])
@admin_require
def admin_slideshow_edit(aid):
    '''
    :param id: 轮播id
    :param name: 轮播名称
    :param rank: 图片排序
    :param imgName:图片名称
    :param href:跳转链接
    :param zone:发布空间 1：首页 2：个人中心 3：功能页
    :return:
    '''
    if not aid.job.imgText:
        return jsonify(code=-103, msg="没有权限")
    id = request.form.get("id", type=int)
    name = request.form.get("name", type=str)
    rank = request.form.get("rank", type=int, default=1)
    imgName = request.form.get("imgName", type=str)
    href = request.form.get("href", type=str)
    zone = request.form.get("zone", type=int)

    if id is None:
        return jsonify(code=-1, msg="轮播id错误")
    # 添加日志
    operate_comment = []
    newView = ViewPager.query.get(id)
    if not newView:
        return jsonify(code=-1, msg="没有找到该条记录")
    if name:
        operate_comment.append({"name": "轮播名称", "raw": newView.name, "content": name})
        newView.name = name

    if rank:
        operate_comment.append({"name": "轮播排序", "raw": newView.rank, "content": rank})
        newView.rank = rank
    if imgName:
        operate_comment.append({"name": "图片名称", "raw": newView.imgName, "content": imgName})
        newView.imgName = imgName
    if href:
        operate_comment.append({"name": "跳转链接", "raw": newView.href, "content": href})
        newView.href = href
    if zone:
        operate_comment.append(
            {"name": "发布空间", "raw": "首页" if newView.zone == 1 else "个人中心" if newView.zone == 2 else "功能页",
             "content": "首页" if zone == 1 else "个人中心" if zone == 2 else "功能页"})
        newView.zone = zone

        log = Admin_operate_log(func="轮播图", up=2, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="修改成功", data={
            "id": newView.id,
            "name": newView.name,
            "imgPath": API_SET.get("QINIU").get("qiniu_url") + newView.imgName,
            "href": newView.href,
            "rank": newView.rank,
            "imgName": newView.imgName,
            "status": newView.status,
            "zone": newView.zone,
            "createtime": str(newView.createtime),
            "updateTime": str(newView.updateTime)
        })
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败，服务器出错了，请稍后重试")


# 获取轮播图
@app.route('/pdd/admin/slideshow', methods=["post", "get"])
@admin_require
def admin_slideshow(aid):
    '''


    :param page:页码
    :param keyword:搜索关键词
    :param status:状态
    :param zone:空间 1：首页 2：个人中心 3：功能页
    :return:
    '''
    page = request.args.get('page', default=0, type=int)
    keyword = request.args.get("keyword", type=str)
    status = request.args.get("status", type=inputs.boolean)
    zone = request.args.get("zone", type=int)
    pageSize = request.args.get('pageSize', default=10, type=int)
    sql = list()
    csql = list()
    if keyword:
        sql.append(ViewPager.name.like(f"%{keyword}%"))
    if status is not None:
        sql.append(ViewPager.status == status)
    if zone:
        sql.append(ViewPager.zone == zone)
        csql.append(ViewPager.zone == zone)

    pagerCount = db.session.query(ViewPager.status, db.func.count(ViewPager.status).label("up"),
                                  ).filter(*csql).group_by(
        ViewPager.status).all()
    pagerCount = {i.status: i.up for i in pagerCount}
    pager = ViewPager.query.filter(*sql).paginate(page, per_page=pageSize, error_out=False)

    data = []
    for i in pager.items:
        data.append({
            "id": i.id,
            "name": i.name,
            "imgPath": API_SET.get("QINIU").get("qiniu_url") + i.imgName,
            "href": i.href,
            "rank": i.rank,
            "imgName": i.imgName,
            "status": i.status,
            "zone": i.zone,
            "createtime": str(i.createtime),
            "updateTime": str(i.updateTime)
        })
    return jsonify(code=0, msg="成功",
                   page=pager.page,
                   total=pager.total,
                   pages=pager.pages,
                   rows=data,
                   up=pagerCount.get(True) if pagerCount.get(True) else 0,
                   down=pagerCount.get(False) if pagerCount.get(False) else 0,

                   )


# 轮播图上下线
@app.route('/pdd/admin/slideshow/downUp', methods=["post", "get"])
@admin_require
def admin_slideshow_downUp(aid):
    '''


    :param id:轮播id
    :param status:状态
    :return:
    '''
    if not aid.job.imgText:
        return jsonify(code=-103, msg="没有权限")
    id = request.form.get('id', default=0, type=int)
    status = request.form.get("status", type=inputs.boolean)

    if id is None:
        return jsonify(code=-1, msg="id不能为空")
    if status is None:
        return jsonify(code=-1, msg="status不能为空")

    pager = ViewPager.query.get(id)
    if not pager:
        return jsonify(code=-1, msg="没后找到该条记录")
    operate_comment = []
    operate_comment.append({"name": "轮播名称", "content": pager.name})
    operate_comment.append(
        {"name": "操作", "content": "上线" if status else "下线"})
    log = Admin_operate_log(func="轮播图", up=4, comment=operate_comment, aid=aid.id)
    try:

        pager.status = status
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="修改成功")
    except:
        db.session.rollback()

        return jsonify(code=-1, msg="修改失败")


# 轮播图删除
@app.route('/pdd/admin/slideshow/delete', methods=["post", "get"])
@admin_require
def admin_slideshow_delete(aid):
    '''


    :param id:轮播id
    :param status:状态
    :return:
    '''
    if not  aid.job.imgText:
        return jsonify(code=-103, msg="没有权限")
    id = request.form.get('id', default=0, type=int)
    if id is None:
        return jsonify(code=-1, msg="id不能为空")

    pager = ViewPager.query.get(id)
    if not pager:
        return jsonify(code=-1, msg="没后找到该条记录")

    operate_comment = []
    operate_comment.append({"name": "轮播名称", "content": pager.name})
    log = Admin_operate_log(func="轮播图", up=3, comment=operate_comment, aid=aid.id)

    try:
        QiniuDel(pager.imgName)
        db.session.delete(pager)
        db.session.add(log)
        db.session.commit()

        return jsonify(code=0, msg="删除成功")
    except:
        db.session.rollback()

        return jsonify(code=-1, msg="删除失败")


'''
功能数据处理
'''


# 获取功能数据
@app.route('/pdd/admin/func', methods=["post", "get"])
@admin_require
def admin_func(aid):
    '''
    :param status:上下线
    :return:
    '''
    status = request.args.get("status", type=inputs.boolean)
    keyword = request.args.get("keyword", type=str)
    sql = list()
    if status is not None:
        sql.append(FuncData.status == status)
    if keyword:
        sql.append(FuncData.name.like(f"%{keyword}%"))
    pagerCount = db.session.query(FuncData.status, db.func.count(FuncData.status).label("up"),
                                  ).group_by(
        FuncData.status).all()
    pagerCount = {i.status: i.up for i in pagerCount}
    func = FuncData.query.filter(*sql).all()
    data = []
    for i in func:
        data.append({
            "id": i.id,
            "imgPath": API_SET.get("QINIU").get("qiniu_url") + i.imgName if i.imgName else None,
            "imgName": i.imgName,
            "integral": i.integral,
            "intro":i.intro,
            "href": i.href,
            "name": i.name,
            "rank": i.rank,
            "status": i.status,
            "comment": i.comment if i.status else "",
            "content": i.content if i.content else "",
            "useCount": i.useCount,
            "createtime": str(i.createtime),
            "updateTime": str(i.updateTime)
        })
    return jsonify(code=0, msg="成功",
                   rows=data,
                   up=pagerCount.get(True) if pagerCount.get(True) else 0,
                   down=pagerCount.get(False) if pagerCount.get(False) else 0,
                   )


# 修改功能数据
@app.route('/pdd/admin/func/eidt', methods=["post", "get"])
@admin_require
def admin_func_edit(aid):
    if aid.job.func == -1:
        return jsonify(code=-103, msg="没有权限")
    '''
    :param id:功能id
    :param imgName:图片名
    :param rank:排序
    :param useCount:初始使用量
    :param integral:使用积分
    :param href:跳转链接
    :return:
    '''
    id = request.form.get("id", type=int)
    imgName = request.form.get("imgName", type=str)
    rank = request.form.get("rank", type=int)
    useCount = request.form.get("useCount", type=int)
    integral = request.form.get("integral", type=int)
    href = request.form.get("href", type=str)
    intro = request.form.get("intro",type=str)
    if id is None:
        return jsonify(code=-1, msg="id不能为空")

    func = FuncData.query.get(id)
    if not func:
        return jsonify(code=-1, msg="没有找到该条记录，请刷新重试")
    operate_comment = []

    if integral:
        if integral != func.integral:
            if aid.job.price == -1:
                return jsonify(code=-103, msg="没有修改积分的权限")
            operate_comment.append({"name": "使用积分", "raw": func.integral, "content": integral})
            func.integral = integral

    if imgName:
        QiniuDel(func.imgName)
        operate_comment.append({"name": "功能图片", "raw": func.imgName, "content": imgName})
        func.imgName = imgName

    if intro:
        operate_comment.append({"name": "功能图片", "raw": func.intro, "content": intro})
        func.intro = intro

    if rank:
        operate_comment.append({"name": "功能排序", "raw": func.rank, "content": rank})
        func.rank = rank

    if useCount:
        operate_comment.append({"name": "初始使用", "raw": func.useCount, "content": useCount})
        func.useCount = useCount



    if href:
        operate_comment.append({"name": "跳转链接", "raw": func.href, "content": href})
        func.href = href

    log = Admin_operate_log(func=func.name + "功能数据", up=2, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="修改成功", data={
            "id": func.id,
            "imgPath": API_SET.get("QINIU").get("qiniu_url") + func.imgName if func.imgName else None,
            "imgName": func.imgName,
            "integral": func.integral,
            "intro": func.intro,
            "href": func.href,
            "name": func.name,
            "rank": func.rank,
            "status": func.status,
            "comment": func.comment if func.status else "",
            "content": func.content,
            "useCount": func.useCount,
            "createtime": str(func.createtime),
            "updateTime": str(func.updateTime)
        })
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败，服务器出错了，请稍后重试")


# 修改功能说明
@app.route('/pdd/admin/func/content/eidt', methods=["post", "get"])
@admin_require
def admin_func_content_eidt(aid):
    if aid.job.func == -1:
        return jsonify(code=-103, msg="没有权限")
    '''
    :param id:功能id
    :param content:使用说明内容

    :return:
    '''
    id = request.form.get("id", type=int)
    content = request.form.get("content", type=str)

    if id is None:
        return jsonify(code=-1, msg="id不能为空")

    func = FuncData.query.get(id)
    if not func:
        return jsonify(code=-1, msg="没有找到该条记录，请刷新重试")
    operate_comment = []

    if content:
        operate_comment.append({"name": "使用说明", "raw": "内容过长不给予显示...", "content": "内容过长不给予显示..."})
        func.content = content

    log = Admin_operate_log(func=func.name + "使用说明", up=2, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="修改成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败，服务器出错了，请稍后重试")


# 功能维护
@app.route('/pdd/admin/func/downUp', methods=["post", "get"])
@admin_require
def admin_func_downUp(aid):
    if aid.job.func == -1:
        return jsonify(code=-103, msg="没有权限")
    '''
    :param id:功能id
    :param status:上下线

    :return:
    '''
    id = request.form.get("id", type=int)
    status = request.form.get("status", type=inputs.boolean)
    comment = request.form.get("comment", type=str)
    if id is None:
        return jsonify(code=-1, msg="id不能为空")
    if status is None:
        return jsonify(code=-1, msg="status不能为空")
    if status is not None:
        if not status:
            if comment is None:
                return jsonify(code=-1, msg="维护的说明不能为空")

    func = FuncData.query.get(id)
    if not func:
        return jsonify(code=-1, msg="没有找到该条记录，请刷新重试")
    operate_comment = []
    operate_comment.append({"name": "功能名称", "content": func.name})
    operate_comment.append(
        {"name": "操作", "content": "上线" if status else "下线"})
    func.status = status
    func.comment = comment

    log = Admin_operate_log(func="功能", up=4, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="修改成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败，服务器出错了，请稍后重试")


'''
文章发布管理
'''


# 发布文章
@app.route('/pdd/admin/upload/article', methods=["post", "get"])
@admin_require
def admin_upload_article(aid):
    '''
    :param title = db.Column(db.String(225),nullable=False,comment="标题")
    :param content = db.Column(db.TEXT,nullable=False,comment="文章内容")
    :param category = db.Column(db.Integer,nullable=False,comment="1:运营案例 2电商资讯 3学习园地 4直通车")
    :param cover = db.Column(db.String(225),nullable=False,comment="封面")
    :param read = db.Column(db.Integer,nullable=False,comment="初始阅读数量")
    :param intro = db.Column(db.TEXT, nullable=False, comment="文章简介")
    :param original = db.Column(db.Boolean, nullable=False, comment="是否原创")
    :param Istop = db.Column(db.Boolean, nullable=False, comment="是否置顶")
    :param releaseTime = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now, comment='发布时间')
    :return:
    '''
    '''
    :param id:功能id
    :param status:上下线

    :return:
    '''
    title = request.form.get("title", type=str)
    content = request.form.get("content", type=str)
    category = request.form.get("category", type=int)
    cover = request.form.get("cover", type=str)
    read = request.form.get("read", type=int)
    intro = request.form.get("intro", type=str)
    original = request.form.get("original", type=inputs.boolean)
    releaseTime = request.form.get("releaseTime", type=str)
    operate_comment = []
    if title is None:
        return jsonify(code=-1, msg="文章标题不能为空")
    if content is None:
        return jsonify(code=-1, msg="文章内容不能为空")
    if category is None:
        return jsonify(code=-1, msg="文章类目不能为空")
    if read is None:
        return jsonify(code=-1, msg="文章初始点赞不能为空")
    if intro is None:
        return jsonify(code=-1, msg="请输入点文章简介吧")
    if original is None:
        return jsonify(code=-1, msg="请选择是否原创")

    aobj = Article(title=title, content=content, category=category, cover=cover, read=read,
                   intro=intro, original=original, Istop=False, releaseTime=releaseTime, flag=1, admin_id=aid.id)
    operate_comment.append({"name": "文章标题", "content": aobj.title})
    operate_comment.append({"name": "是否置顶", "content": "置顶" if aobj.Istop else "非置顶"})
    log = Admin_operate_log(func="文章", up=1, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(aobj)
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="发布成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="发布失败")


# 编辑文章
@app.route('/pdd/admin/upload/article/edit', methods=["post", "get"])
@admin_require
def admin_upload_article_edit(aid):
    '''
    :param id = 文章id
    :param title = db.Column(db.String(225),nullable=False,comment="标题")
    :param content = db.Column(db.TEXT,nullable=False,comment="文章内容")
    :param category = db.Column(db.Integer,nullable=False,comment="1:运营案例 2电商资讯 3学习园地 4直通车")
    :param cover = db.Column(db.String(225),nullable=False,comment="封面")
    :param read = db.Column(db.Integer,nullable=False,comment="初始阅读数量")
    :param intro = db.Column(db.TEXT, nullable=False, comment="文章简介")
    :param original = db.Column(db.Boolean, nullable=False, comment="是否原创")
    :param Istop = db.Column(db.Boolean, nullable=False, comment="是否置顶")
    :param releaseTime = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now, comment='发布时间')
    :return:
    '''
    '''
    :param id:功能id
    :param status:上下线

    :return:
    '''
    id = request.form.get("id", type=int)
    title = request.form.get("title", type=str)
    content = request.form.get("content", type=str)
    category = request.form.get("category", type=int)
    cover = request.form.get("cover", type=str)
    read = request.form.get("read", type=int)
    intro = request.form.get("intro", type=str)
    original = request.form.get("intro", type=inputs.boolean)
    releaseTime = request.form.get("releaseTime", type=str)
    operate_comment = []

    if aid.job.imgText:

        aobj = Article.query.get(id)

    else:
        aobj = Article.query.filter(Article.admin_id==aid.id,Article.id==id).first()

    if not aobj:
        return jsonify(code=0, msg="未找到该条记录")

    if title:
        operate_comment.append({"name": "文章标题", "raw": aobj.title, "content": title})
        aobj.title = title

    if content:
        operate_comment.append({"name": "文章内容", "raw": '内容过长不给予显示...', "content": "内容过长不给予显示..."})
        aobj.content = content
    if cover:
        QiniuDel(aobj.cover)
        operate_comment.append({"name": "文章封面", "raw": aobj.cover, "content": cover})
        aobj.cover = cover

    if category:
        operate_comment.append({"name": "文章类目",
                                "raw": "运营案例" if aobj.category == 1 else "电商资讯" if aobj.category == 2 else "学习园地" if aobj.category == 3 else "直通车" if aobj.category == 4 else "未知",
                                "content": "运营案例" if category == 1 else "电商资讯" if category == 2 else "学习园地" if category == 3 else "直通车" if category == 4 else "未知"})
        aobj.category = category

    if read:
        operate_comment.append({"name": "阅读数量", "raw": aobj.read, "content": read})
        aobj.read = read
    if intro:
        operate_comment.append({"name": "文章简介", "raw": '内容过长不给予显示...', "content": "内容过长不给予显示..."})
        aobj.intro = intro
    if original:
        operate_comment.append(
            {"name": "是否原创", "raw": "原创" if aobj.original else "非原创", "content": "原创" if original else "非原创"})
        aobj.original = original
    if releaseTime:
        operate_comment.append({"name": "定时发布", "raw": str(aobj.releaseTime), "content": releaseTime})
        aobj.releaseTime = releaseTime

    log = Admin_operate_log(func="文章", up=2, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="发布成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="发布失败")


# 保存草稿
@app.route('/pdd/admin/upload/article/draft', methods=["post", "get"])
@admin_require
def admin_upload_article_draft(aid):
    '''
    :param title = db.Column(db.String(225),nullable=False,comment="标题")
    :param content = db.Column(db.TEXT,nullable=False,comment="文章内容")
    :param category = db.Column(db.Integer,nullable=False,comment="1:运营案例 2电商资讯 3学习园地 4直通车")
    :param cover = db.Column(db.String(225),nullable=False,comment="封面")
    :param read = db.Column(db.Integer,nullable=False,comment="初始阅读数量")
    :param intro = db.Column(db.TEXT, nullable=False, comment="文章简介")
    :param original = db.Column(db.Boolean, nullable=False, comment="是否原创")
    :param Istop = db.Column(db.Boolean, nullable=False, comment="是否置顶")
    :param releaseTime = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now, comment='发布时间')
    :return:
    '''

    '''
    :param id:功能id
    :param status:上下线

    :return:
    '''
    id = request.form.get("id", type=int)
    title = request.form.get("title", type=str)
    content = request.form.get("content", type=str)
    category = request.form.get("category", type=int)
    cover = request.form.get("cover", type=str)
    read = request.form.get("read", type=int)
    intro = request.form.get("intro", type=str)
    original = request.form.get("original", type=inputs.boolean)
    releaseTime = request.form.get("releaseTime", type=str)
    if id is None:
        if title is None:
            return jsonify(code=-1, msg="文章标题不能为空")
        if content is None:
            return jsonify(code=-1, msg="文章内容不能为空")
        if category is None:
            return jsonify(code=-1, msg="文章类目不能为空")
        if read is None:
            return jsonify(code=-1, msg="文章初始点赞不能为空")
        if intro is None:
            return jsonify(code=-1, msg="请输入点文章简介吧")
        if original is None:
            return jsonify(code=-1, msg="请选择是否原创")
        aobj = Article(title=title, content=content, category=category, cover=cover, read=read,
                       intro=intro, original=original, Istop=False, releaseTime=releaseTime, flag=3, admin_id=aid.id)
        try:
            db.session.add(aobj)
            db.session.commit()
            return jsonify(code=0, msg="保存到草稿成功", id=aobj.id)
        except:
            db.session.rollback()
            return jsonify(code=-1, msg="保存到草稿失败")
    else:
        aobj = Article.query.filter(Article.admin_id == aid.id, Article.id == id).first()
        if not aobj:
            return jsonify(code=-1, msg="没找到该条记录,保存到草稿箱重试", id=aobj.id)

        if title:
            aobj.title = title

        if content:
            aobj.content = content
        if cover:
            aobj.cover = cover

        if category:
            aobj.category = category

        if read:
            aobj.read = read
        if intro:
            aobj.intro = intro
        if original:
            aobj.original = original
        if releaseTime:
            aobj.releaseTime = releaseTime

        try:
            db.session.commit()
            return jsonify(code=0, msg="保存成功", id=aobj.id)
        except:
            db.session.rollback()
            return jsonify(code=-1, msg="预览失败,请先保存到草稿箱重试")


# 预览内容
@app.route('/pdd/admin/article/preview', methods=["get"])
@admin_require
def admin_article_preview(aid):
    id = request.args.get("id", type=int)
    if id is None:
        return jsonify(code=-1, msg="文章id不能为空")

    aobj = Article.query.get(id)
    if not aobj:
        return jsonify(code=-1, msg="没找到该文章")

    return jsonify(code=0, msg="获取成功", data={
        "title": aobj.title,
        "content": aobj.content,
        "category": "运营案例" if aobj.category == 1 else "电商资讯" if aobj.category == 2 else "学习园地" if aobj.category == 3 else "直通车" if aobj.category == 4 else "未知",
        "read": aobj.read,
        "original": "原创" if aobj.original else "非原创",
        "Istop": aobj.Istop,
    })


# 获取草稿列表
@app.route('/pdd/admin/article/draft/list', methods=["get"])
@admin_require
def admin_article_draft_list(aid):
    page = request.args.get("page", default=1, type=int)
    pageSize = request.args.get("pageSize", default=10, type=int)
    keyword = request.args.get("keyword", type=str)
    sql = list()
    if keyword:
        sql.append(Article.title.like(f"%{keyword}%"))

    aobj = Article.query.filter(*sql).filter(Article.admin_id == aid.id, Article.flag == 3).paginate(page,
                                                                                                     per_page=pageSize,
                                                                                                     error_out=False)

    data = []
    for i in aobj.items:
        data.append({
            "id": i.id,
            "title": i.title,
            "content": html_to_plain_text(i.content),
            "category": "运营案例" if i.category == 1 else "电商资讯" if i.category == 2 else "学习园地" if i.category == 3 else "直通车" if i.category == 4 else "未知",
            "read": i.read,
            "original": "原创" if i.original else "非原创",
            "Istop": "置顶" if i.Istop else "非置顶",
            "cover": API_SET.get("QINIU").get("qiniu_url") + i.cover,
            "intro": i.intro,
            "updateTime": str(i.updateTime)
        })
    return jsonify(code=0, msg="成功",
                   page=aobj.page,
                   total=aobj.total,
                   pages=aobj.pages,
                   rows=data,
                   )


# 获取草稿内容
@app.route('/pdd/admin/article/draft', methods=["get"])
@admin_require
def admin_article_draft(aid):
    id = request.args.get("id", type=int)
    if id is None:
        return jsonify(code=-1, msg="文章id不能为空")

    aobj = Article.query.filter(Article.admin_id == aid.id, Article.id == id, Article.flag == 3).first()
    if not aobj:
        return jsonify(code=-104, msg="没找到该草稿内容")

    return jsonify(code=0, msg="获取成功", data={
        "id": aobj.id,
        "title": aobj.title,
        "content": aobj.content,
        "category": aobj.category,
        "read": aobj.read,
        "original": aobj.original,
        "Istop": aobj.Istop,
        "cover": aobj.cover,
        "intro": aobj.intro,

    })


# 删除草稿内容
@app.route('/pdd/admin/article/delete', methods=["get"])
@admin_require
def admin_article_draft_delete(aid):
    id = request.args.get("id", type=int)
    if id is None:
        return jsonify(code=-1, msg="文章id不能为空")

    aobj = Article.query.filter(Article.admin_id == aid.id, Article.id == id, Article.flag == 3).first()
    if not aobj:
        return jsonify(code=-1, msg="没找到该条草稿记录，请刷新重试")

    try:
        QiniuDel(aobj.cover)
        db.session.delete(aobj)
        db.session.commit()
        return jsonify(code=0, msg="删除成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="删除失败")

# 获取文章列表
@app.route('/pdd/admin/article/list', methods=["post", "get"])
@admin_require
def admin_article_list(aid):
    '''
    :param status:0：全部 1：在线 2：停用 3：转码中
    :param sort:1:综合 2:按时间 3:按播放
    :return:
    '''
    status = request.args.get("status", type=int)
    sort = request.args.get("sort", type=int)
    page = request.args.get("page", default=1, type=int)
    keyword = request.args.get("keyword", type=str)
    pageSize = request.args.get('pageSize', default=10, type=int)
    sql = list()
    sortSql = list()
    countsql = list()
    countsql.append(Article.flag.in_([1,2]))
    sql.append(Article.flag.in_([1,2]))
    if not aid.job.imgText:
        sql.append(Article.admin_id == aid.id)
        countsql.append(Article.admin_id==aid.id)

    if status and status in [1,2]:
        sql.append(Article.flag == status)
    if keyword:
        sql.append(Article.title.like(f"%{keyword}%"))
    if sort == 1:
        sortSql.append(Article.read.desc())
        sortSql.append(Article.createtime.desc())
    if sort == 2:
        sortSql.append(Article.createtime.desc())
    if sort == 3:
        sortSql.append(Article.read.desc())

    flagCount = db.session.query(Article.flag, db.func.count(Article.id).label("count"),
                                 ).filter(*countsql).group_by(
        Article.flag).all()
    flagCount = {i.flag: i.count for i in flagCount}
    article = Article.query.filter(*sql).order_by(*sortSql).paginate(page, per_page=pageSize, error_out=False)
    data = []
    for i in article.items:
        data.append({
            "id": i.id,
            "username":i.admin.username,
            "title": i.title,
            "content": html_to_plain_text(i.content),
            "category": "运营案例" if i.category == 1 else "电商资讯" if i.category == 2 else "学习园地" if i.category == 3 else "直通车" if i.category == 4 else "未知",
            "read": i.read,
            "original": "原创" if i.original else "非原创",
            "Istop": i.Istop,
            "cover": API_SET.get("QINIU").get("qiniu_url") + i.cover,
            "intro": i.intro,
            "updateTime": str(i.updateTime),
            "flag":i.flag,
        })
    return jsonify(code=0, msg="成功",
                   rows=data,
                   page=article.page,
                   total=article.total,
                   pages=article.pages,
                   up=flagCount.get(1) if flagCount.get(1) else 0,
                   down=flagCount.get(2) if flagCount.get(2) else 0,
                   )


# 文章上下线
@app.route('/pdd/admin/article/downUp', methods=["post", "get"])
@admin_require
def admin_article_downUp(aid):

    id = request.form.get("id", type=int)
    status = request.form.get("status",type=int)
    if status is None and status not in [1,2]:
        return jsonify(code=-1, msg="请求出错")

    if id is None:
        return jsonify(code=-1, msg="请求出错")

    article = Article.query.filter(Article.id == id).first()
    if not article:
        return jsonify(code=-1, msg="请求出错")

    if not aid.job.imgText:
        if article.admin_id != aid.id:
            return jsonify(code=-103, msg="没有权限")

    try:
        operate_comment = []
        operate_comment.append({"name": "文章标题", "content": article.title})
        operate_comment.append(
            {"name": "操作", "content": "上线" if status==1 else "下线"})
        log = Admin_operate_log(func="文章", up=4, comment=operate_comment, aid=aid.id)

        db.session.add(log)
        article.flag = status
        db.session.commit()
        return jsonify(code=0, msg="请求成功",flag=article.flag)
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="请求出错", flag=article.flag)


# 获取文章内容
@app.route('/pdd/admin/article/content', methods=["get"])
@admin_require
def admin_article_content(aid):
    id = request.args.get("id", type=int)
    if id is None:
        return jsonify(code=-1, msg="文章id不能为空")
    sql = list()
    sql.append(Article.id == id)
    sql.append(Article.flag.in_([1, 2]))
    if not aid.job.imgText:
        sql.append(Article.admin_id == aid.id)

    aobj = Article.query.filter(*sql).first()
    if not aobj:
        return jsonify(code=-104, msg="没找到该草稿内容")

    return jsonify(code=0, msg="获取成功", data={
        "id": aobj.id,
        "title": aobj.title,
        "content": aobj.content,
        "category": aobj.category,
        "read": aobj.read,
        "original": aobj.original,
        "cover": aobj.cover,
        "intro": aobj.intro,

    })


# 文章置顶
@app.route('/pdd/admin/article/recommend', methods=["post", "get"])
@admin_require
def admin_article_recommend(aid):
    id = request.form.get("id", type=int)
    istop = request.form.get("istop", type=inputs.boolean)
    if istop is None:
        return jsonify(code=-1, msg="请求出错")

    if id is None:
        return jsonify(code=-1, msg="请求出错")

    article = Article.query.filter(Article.id == id).first()
    if not article:
        return jsonify(code=-1, msg="请求出错")

    if not aid.job.imgText:
        if article.admin_id != aid.id:
            return jsonify(code=-103, msg="没有权限")

    try:
        operate_comment = []
        operate_comment.append(
            {"name": "视频标题", "raw": article.title, "content": article.title})
        operate_comment.append(
            {"name": "是否会员可看", "raw": "开启" if article.Istop else "关闭", "content": "开启" if istop else "关闭"})
        log = Admin_operate_log(func="视频", up=2, comment=operate_comment, aid=aid.id)
        db.session.add(log)
        article.Istop = istop
        db.session.commit()
        return jsonify(code=0, msg="请求成功", Istop=article.Istop)
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="请求出错", Istop=article.Istop)

# 删除文章
@app.route('/pdd/admin/article/del', methods=["post", "get"])
@admin_require
def admin_article_del(aid):


    id = request.form.get("id", type=int)

    if id is None:
        return jsonify(code=-1, msg="请求出错")

    article = Article.query.filter(Article.id == id,Article.flag.in_([1,2])).first()
    if not article:
        return jsonify(code=-1, msg="请求出错")

    if not aid.job.imgText:
        if article.admin_id != aid.id:
            return jsonify(code=-103, msg="没有权限")

    try:
        QiniuDel(article.cover)
        operate_comment = []
        operate_comment.append({"name": "文章标题", "content": article.title})
        log = Admin_operate_log(func="文章", up=3, comment=operate_comment, aid=aid.id)
        db.session.add(log)
        db.session.delete(article)
        db.session.commit()
        return jsonify(code=0, msg="删除成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="删除出错")




'''
视频投稿

'''


# 发布视频
@app.route('/pdd/admin/upload/video', methods=["post", "get"])
@admin_require
def admin_upload_video(aid):
    '''
    :param title = db.Column(db.String(225),nullable=False,comment="标题")
    :param videoName = db.Column(db.String(225), nullable=True, comment="视频源")
    :param cover = db.Column(db.String(225), nullable=True, comment="封面")
    :param live = db.Column(db.String(225),nullable=False,comment="m3u8流")
    :param read = db.Column(db.Integer,nullable=False,comment="初始观看数量")
    :param intro = db.Column(db.TEXT, nullable=False, comment="视频简介")
    :param duration = db.Column(db.Float, nullable=False, comment="视频时长")
    :param original = db.Column(db.Boolean, nullable=False, comment="是否原创")
    :param Istop = db.Column(db.Boolean, nullable=False, comment="是否发布")
    :param flag = db.Column(db.Integer,nullable=False,comment="1:发布 2:下线 3:转码中")
    :param releaseTime = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now, comment='发布时间')
    :param createtime = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now, comment='创建时间')
    :param updateTime = db.Column(db.DateTime, default=datetime.datetime.now, onupdate=datetime.datetime.now)
    :return:
    '''
    data = request.json
    if data is None:
        return jsonify(code=-1, msg='参数错误')
    if type(data) !=dict:
        return jsonify(code=-1, msg='参数错误')
    title = data.get("title")
    videoName = data.get("videoName")
    cover = data.get("cover")
    read = data.get("read")
    intro = data.get("intro")
    duration = data.get("duration")
    original = data.get("original")
    isVip = data.get("isVip")
    releaseTime = data.get("releaseTime")
    coverList = data.get("coverList")

    operate_comment = []
    if title is None:
        return jsonify(code=-1, msg="视频标题不能为空")
    if videoName is None:
        return jsonify(code=-1, msg="视频源不能为空")
    if cover is None:
        return jsonify(code=-1, msg="视频封面不能为空")
    if read is None:
        return jsonify(code=-1, msg="视频初始阅读不能为空")
    if intro is None:
        return jsonify(code=-1, msg="请输入点文章简介吧")
    if duration is None:
        return jsonify(code=-1, msg="视频时长不能为空")
    if original is None:
        return jsonify(code=-1, msg="请选择是否原创")
    if coverList:
        if type(coverList) != list:
            return jsonify(code=-1, msg="封面组图请传入list类型")


    persistentId = pfop_m3u8(videoName, aid.nick).get("persistentId")
    if not persistentId:
        return jsonify(code=-1, msg="预转码创建失败")
    aobj = Video(title=title, persistentId=persistentId, videoName=videoName, cover=cover,coverList=coverList, read=read,
                 intro=intro, duration=duration, original=original, isVip=isVip, Istop=False, releaseTime=releaseTime,
                 flag=3, admin_id=aid.id)
    operate_comment.append({"name": "视频标题", "content": aobj.title})
    log = Admin_operate_log(func="视频", up=1, comment=operate_comment, aid=aid.id)
    try:

        db.session.add(aobj)
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="发布成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="发布失败")


# 获取视频列表
@app.route('/pdd/admin/video', methods=["post", "get"])
@admin_require
def admin_video(aid):
    '''
    :param status:0：全部 1：在线 2：停用 3：转码中
    :param sort:1:综合 2:按时间 3:按播放
    :return:
    '''
    status = request.args.get("status", type=int)
    sort = request.args.get("sort", type=int)
    page = request.args.get("page", default=1, type=int)
    keyword = request.args.get("keyword", type=str)
    pageSize = request.args.get('pageSize', default=10, type=int)
    sql = list()
    sortSql = list()
    if not aid.job.imgText:
        sql.append(Video.admin_id == aid.id)
    if status:
        sql.append(Video.flag == status)
    if keyword:
        sql.append(Video.title.like(f"%{keyword}%"))
    if sort == 1:
        sortSql.append(Video.read.desc())
        sortSql.append(Video.createtime.desc())
    if sort == 2:
        sortSql.append(Video.createtime.desc())
    if sort == 3:
        sortSql.append(Video.read.desc())

    flagCount = db.session.query(Video.flag, db.func.count(Video.id).label("count"),
                                 ).group_by(
        Video.flag).all()
    flagCount = {i.flag: i.count for i in flagCount}
    video = Video.query.filter(*sql).order_by(*sortSql).paginate(page, per_page=pageSize, error_out=False)
    data = []
    for i in video.items:
        data.append({
            "id": i.id,
            "title": i.title,
            "coverPath": API_SET.get("QINIU").get("qiniu_url") + i.cover,
            "cover": i.cover,
            "videoName": i.videoName,
            "read": i.read,
            "intro": i.intro,
            "original": i.original,
            "Istop": i.Istop,
            "flag": i.flag,
            "isVip": i.isVip,
            "username": i.admin.username,
            "createtime": str(i.createtime),
            "updateTime": str(i.updateTime),
            "duration": i.duration,
        })
    return jsonify(code=0, msg="成功",
                   rows=data,
                   page=video.page,
                   total=video.total,
                   pages=video.pages,
                   up=flagCount.get(1) if flagCount.get(1) else 0,
                   down=flagCount.get(2) if flagCount.get(2) else 0,
                   turn=flagCount.get(3) if flagCount.get(3) else 0,
                   )


# 获取视频
@app.route('/pdd/admin/video/data', methods=["post", "get"])
@admin_require
def admin_video_data(aid):
    '''
    :param status:0：全部 1：在线 2：停用 3：转码中
    :param sort:1:综合 2:按时间 3:按播放
    :return:
    '''
    id = request.args.get("id", type=int)
    if id is None:
        return jsonify(code=-1, msg="请求出错")

    video = Video.query.filter(Video.id == id).first()
    if not video:
        return jsonify(code=-1, msg="请求出错")
    if not aid.job.imgText:
        if video.admin_id != aid.id:
            return jsonify(code=-103, msg="没有权限编辑此视频")

    return jsonify(code=0, msg="获取成功",
                   data={
                       "id": video.id,
                       "title": video.title,
                       "coverPath": API_SET.get("QINIU").get("qiniu_url") + video.cover,
                       "cover": video.cover,
                       "videoName": video.videoName,
                       "read": video.read,
                       "intro": video.intro,
                       "original": video.original,
                       "Istop": video.Istop,
                       "flag": video.flag,
                       "isVip": video.isVip,
                       "username": video.admin.username,
                       "createtime": str(video.createtime),
                       "updateTime": str(video.updateTime),
                       "coverList":video.coverList,
                       "duration":video.duration,
                   }
                   )

# 推荐视频
@app.route('/pdd/admin/video/recommend', methods=["post", "get"])
@admin_require
def admin_video_recommend(aid):
    '''
    :param status:0：全部 1：在线 2：停用 3：转码中
    :param sort:1:综合 2:按时间 3:按播放
    :return:
    '''

    if not aid.job.imgText:

        return jsonify(code=-103, msg="没有权限")

    id = request.form.get("id", type=int)
    istop = request.form.get("istop",type=inputs.boolean)
    if istop is None:
        return jsonify(code=-1, msg="请求出错")

    if id is None:
        return jsonify(code=-1, msg="请求出错")

    video = Video.query.filter(Video.id == id).first()
    if not video:
        return jsonify(code=-1, msg="请求出错")


    try:
        operate_comment = []
        operate_comment.append(
            {"name": "视频标题", "raw": video.title,"content": video.title})
        operate_comment.append(
            {"name": "推荐", "raw": "开启" if video.Istop else "关闭", "content": "开启" if istop else "关闭"})
        log = Admin_operate_log(func="视频", up=2, comment=operate_comment, aid=aid.id)
        db.session.add(log)
        video.Istop = istop
        db.session.commit()
        return jsonify(code=0, msg="请求成功",istop=video.Istop)
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="请求出错", istop=video.Istop)


# 编辑视频
@app.route('/pdd/admin/video/edit', methods=["post", "get"])
@admin_require
def admin_video_edit(aid):
    '''
    :param status:0：全部 1：在线 2：停用 3：转码中
    :param sort:1:综合 2:按时间 3:按播放
    :return:
    '''

    data = request.json
    if data is None:
        return jsonify(code=-1, msg='参数错误')
    if type(data) != dict:
        return jsonify(code=-1, msg='参数错误')
    id = data.get("id")
    title = data.get("title")
    videoName = data.get("videoName")
    cover = data.get("cover")
    read = data.get("read")
    intro = data.get("intro")
    duration = data.get("duration")
    original = data.get("original")
    isVip = data.get("isVip")
    releaseTime = data.get("releaseTime")
    coverList = data.get("coverList")


    if id is None:
        return jsonify(code=-1, msg="id不能为空")

    if aid.job.imgText:
        video = Video.query.filter(Video.id == id).first()
    else:
        video = Video.query.filter(Video.id == id,Video.admin_id==aid.id).first()

    if not video:
        return jsonify(code=-1, msg="没找到该条视频")

    try:
        operate_comment = []


        if videoName is not None and videoName != video.videoName:
            video.videoName = videoName
            operate_comment.append(
                {"name": "视频源", "raw": video.videoName, "content": videoName})
            persistentId = pfop_m3u8(videoName, aid.nick).get("persistentId")
            if not persistentId:
                return jsonify(code=-1, msg="预转码创建失败")
            video.persistentId = persistentId
            video.flag = 3


        if title is not None and title != video.title:
            video.title = title
            operate_comment.append(
                {"name": "视频标题", "raw": video.title, "content": title})


        if cover is not None and cover != video.cover:
            video.cover = cover
            operate_comment.append(
                {"name": "视频封面", "raw": video.cover, "content": cover})
        if read is not None and read != video.read:
            video.read = read
            operate_comment.append(
                {"name": "视频阅读量", "raw": video.read, "content": read})
        if intro is not None and intro != video.intro:
            video.intro = intro
            operate_comment.append(
                {"name": "视频简介", "raw": video.intro[0,20], "content": intro[0,20]})
        if duration is not None and duration != video.duration:
            video.duration = duration

        if original is not None and original != video.original:
            video.original = original

        if isVip is not None and isVip != video.isVip:
            video.isVip = isVip
            operate_comment.append(
                {"name": "是否会员", "raw": "开启" if video.isVip else "关闭", "content": "开启" if isVip else "关闭"})
        if releaseTime is not None and releaseTime != video.releaseTime:
            video.releaseTime = releaseTime
        if coverList is not None:
            video.coverList = coverList

        log = Admin_operate_log(func="视频", up=2, comment=operate_comment, aid=aid.id)
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="修改成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败")


# 视频上下线
@app.route('/pdd/admin/video/downUp', methods=["post", "get"])
@admin_require
def admin_video_downUp(aid):

    id = request.form.get("id", type=int)
    status = request.form.get("status",type=int)
    if status is None:
        return jsonify(code=-1, msg="请求出错")

    if id is None:
        return jsonify(code=-1, msg="请求出错")

    video = Video.query.filter(Video.id == id).first()
    if not video:
        return jsonify(code=-1, msg="请求出错")

    if not aid.job.imgText:
        if video.admin_id != aid.id:
            return jsonify(code=-103, msg="没有权限")

    try:
        operate_comment = []
        operate_comment.append({"name": "视频标题", "content": video.title})
        operate_comment.append(
            {"name": "操作", "content": "上线" if status == 1 else "下线"})
        log = Admin_operate_log(func="视频", up=4, comment=operate_comment, aid=aid.id)
        db.session.add(log)
        video.flag = status
        db.session.commit()
        return jsonify(code=0, msg="请求成功",flag=video.flag)
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="请求出错", flag=video.flag)


# 开启会员可看
@app.route('/pdd/admin/video/isvip', methods=["post", "get"])
@admin_require
def admin_video_isvip(aid):

    id = request.form.get("id", type=int)
    isvip = request.form.get("isvip",type=inputs.boolean)
    if isvip is None:
        return jsonify(code=-1, msg="请求出错")

    if id is None:
        return jsonify(code=-1, msg="请求出错")

    video = Video.query.filter(Video.id == id).first()
    if not video:
        return jsonify(code=-1, msg="请求出错")

    if not aid.job.imgText:
        if video.admin_id != aid.id:
            return jsonify(code=-103, msg="没有权限")

    try:
        operate_comment = []
        operate_comment.append(
            {"name": "视频标题", "raw": video.title, "content": video.title})
        operate_comment.append({"name": "是否会员可看", "raw": "开启" if video.isVip else "关闭", "content": "开启" if isvip else "关闭"})
        log = Admin_operate_log(func="视频", up=2, comment=operate_comment, aid=aid.id)
        db.session.add(log)
        video.isVip = isvip
        db.session.commit()
        return jsonify(code=0, msg="请求成功",isVip=video.isVip)
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="请求出错", isVip=video.isVip)


# 删除视频
@app.route('/pdd/admin/video/del', methods=["post", "get"])
@admin_require
def admin_video_del(aid):


    id = request.form.get("id", type=int)

    if id is None:
        return jsonify(code=-1, msg="请求出错")

    video = Video.query.filter(Video.id == id).first()
    if not video:
        return jsonify(code=-1, msg="请求出错")

    if not aid.job.imgText:
        if video.admin_id != aid.id:
            return jsonify(code=-103, msg="没有权限")

    try:
        QiniuDel(video.videoName)
        QiniuDel(video.live)
        operate_comment = []
        operate_comment.append({"name": "视频标题", "content": video.title})
        log = Admin_operate_log(func="视频", up=3, comment=operate_comment, aid=aid.id)
        db.session.add(log)
        db.session.delete(video)
        db.session.commit()
        return jsonify(code=0, msg="删除成功",flag=video.flag)
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="删除出错", flag=video.flag)

'''
站点设置
'''

# 侧客服栏规则
@app.route('/pdd/admin/setting/ser', methods=["post", "get"])
@admin_require
def admin_setting_ser(aid):

    if not aid.job.imgText:
        return jsonify(code=-103, msg="没有权限")

    type = request.form.get("type", type=str)
    time = request.form.get("time",type=str)

    if type is None or type not in ["随机","轮换"]:
        return jsonify(code=-1, msg="请求出错")

    if time is None or time not in ["五分钟","十分钟","十分钟","半小时","一小时","三小时","半天","一天"]:

        return jsonify(code=-1, msg="请求出错")

    ser = Config.query.filter(Config.key == "Ser").first()
    if not ser:
        return jsonify(code=-1, msg="请求出错")

    try:
        operate_comment = []

        if ser.value.get("type") != type:
            operate_comment.append(
                {"name": "类型", "raw": ser.value.get("type"), "content": type})
            ser.value.update(dict(type=type))
        if ser.value.get("time") != time:
            operate_comment.append(
                {"name": "轮换时间", "raw": ser.value.get("time"), "content": time})
            ser.value.update(dict(time=time))

        flag_modified(ser, 'value')
        log = Admin_operate_log(func="侧客服规则", up=2, comment=operate_comment, aid=aid.id)
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="修改成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败")

# 设置ICP
@app.route('/pdd/admin/setting/ICP', methods=["post", "get"])
@admin_require
def admin_setting_ICP(aid):

    if not aid.job.imgText:
        return jsonify(code=-103, msg="没有权限")

    year = request.form.get("year", type=str)
    company = request.form.get("company",type=str)
    ICP = request.form.get("ICP", type=str)


    icp = Config.query.filter(Config.key == "ICP").first()
    if not icp:
        return jsonify(code=-1, msg="请求出错")

    try:
        operate_comment = []

        if year and icp.value.get("year") != year:
            operate_comment.append(
                {"name": "年份", "raw": icp.value.get("year"), "content": year})
            icp.value.update(dict(year=year))
        if company and icp.value.get("company") != company:
            operate_comment.append(
                {"name": "公司", "raw": icp.value.get("company"), "content": company})
            icp.value.update(dict(company=company))
        if ICP and icp.value.get("ICP") != ICP:
            operate_comment.append(
                {"name": "公司", "raw": icp.value.get("ICP"), "content": ICP})
            icp.value.update(dict(ICP=ICP))

        flag_modified(icp, 'value')
        if len(operate_comment)>0:
            log = Admin_operate_log(func="备案信息", up=2, comment=operate_comment, aid=aid.id)
            db.session.add(log)

        db.session.commit()
        return jsonify(code=0, msg="修改成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败")


# 设置Smoble
@app.route('/pdd/admin/setting/Smobile', methods=["post", "get"])
@admin_require
def admin_setting_Ssmobile(aid):

    if not aid.job.imgText:
        return jsonify(code=-103, msg="没有权限")
    type = request.form.get("type", type=int)
    mobile = request.form.get("mobile", type=str)
    time = request.form.get("time",type=str)

    if type not in [1,2]:
        return jsonify(code=-1, msg="请求出错")

    if type == 1:
        if mobile is None:
            return jsonify(code=-1, msg="请填写客服电话")
    elif type == 2:
        if time is None:
            return jsonify(code=-1, msg="请填写工作时间")
    else:
        return jsonify(code=-1, msg="请求出错")


    smobile = Config.query.filter(Config.key == "Smobile").first()
    if not smobile:
        return jsonify(code=-1, msg="请求出错")

    try:
        operate_comment = []
        if type==1:
            operate_comment.append(
                {"name": "客服电话", "raw": smobile.value.get("mobile"), "content": mobile})
            smobile.value.update(dict(mobile=mobile))
        else:
            operate_comment.append(
                {"name": "工作时间", "raw": smobile.value.get("time"), "content": time})
            smobile.value.update(dict(time=time))

        flag_modified(smobile, 'value')
        log = Admin_operate_log(func="侧栏联系客服", up=2, comment=operate_comment, aid=aid.id)
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="修改成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败")


# 底部客服二维码更换
@app.route('/pdd/admin/setting/footer/ser', methods=["post", "get"])
@admin_require
def admin_setting_footer_ser(aid):

    if not aid.job.imgText:
        return jsonify(code=-103, msg="没有权限")

    type = request.form.get("type", type=int)
    group = request.form.get("group", type=int)
    qr = request.form.get("qr",type=str)
    title = request.form.get("title",type=str)

    if type ==1:
        if qr is None:
            return jsonify(code=-1, msg="二维码不能为空")
    elif type ==2:
        if title is None:
            return jsonify(code=-1, msg="标题不能为空")
    else:
        return jsonify(code=-1, msg="请求错误")


    if group is None or group not in [1,2]:
        return jsonify(code=-1, msg="请求出错")



    ser = Config.query.filter(Config.key == "FSer").first()
    if not ser:
        return jsonify(code=-1, msg="请求出错")

    try:
        operate_comment = []
        if type ==1:
            if group==1:
                if ser.value.get("qr1"):
                    QiniuDel(ser.value.get("qr1"))
                operate_comment.append(
                    {"name": "底部客服一", "raw": ser.value.get("qr1"), "content": qr})
                ser.value.update(dict(qr1=qr))

            else:
                if ser.value.get("qr2"):
                    QiniuDel(ser.value.get("qr2"))
                operate_comment.append(
                    {"name": "底部客服二", "raw": ser.value.get("qr2"), "content": qr})
                ser.value.update(dict(qr2=qr))
        else:
            if group == 1:
                operate_comment.append(
                    {"name": "位置1标题", "raw": ser.value.get("titel1"), "content": title})
                ser.value.update(dict(title1=title))

            else:
                operate_comment.append(
                    {"name": "位置2标题", "raw": ser.value.get("titel2"), "content": title})
                ser.value.update(dict(title2=title))

        flag_modified(ser, 'value')
        log = Admin_operate_log(func="底部客服", up=2, comment=operate_comment, aid=aid.id)
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="修改成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败")



# 获取站点配置
@app.route('/pdd/admin/config', methods=["post", "get"])
@admin_require
def admin_config(aid):

    if not aid.job.imgText:
        return jsonify(code=-103, msg="没有权限")


    ret = Config.query.all()

    return jsonify(code=0,msg='获取成功',data={i.key:i.value for i in ret})


# 添加侧栏客服
@app.route('/pdd/admin/ser/add', methods=["post", "get"])
@admin_require
def admin_ser_add(aid):
    '''
    qr = db.Column(db.String(225),nullable=False,comment="二维码")
    title = db.Column(db.String(20),nullable=False,comment="二维码")
    name = db.Column(db.String(10),nullable=False,comment="姓名")
    flag = db.Column(db.Boolean,nullable=False)
    time = db.Column(db.String(20),nullable=False,comment="时间")
    rotateTime = db.Column(db.DateTime, nullable=False, default=datetime.datetime.now, comment='创建时间')

    :param aid:
    :return:
    '''
    if not aid.job.imgText:
        return jsonify(code=-103, msg="没有权限")


    qr = request.form.get("qr",type=str)
    title = request.form.get("title", type=str)
    name = request.form.get("name", type=str)
    time = request.form.get("time", type=str)
    if qr is None:
        return jsonify(code=-1,msg="请设置二维码图片")
    if title is None:
        return jsonify(code=-1,msg="请设置标题")
    if name is None:
        return jsonify(code=-1, msg="请填写姓名")
    if time is None:
        return jsonify(code=-1, msg="请填写工作时间")
    operate_comment = []

    ser = Service(qr=qr,title=title,name=name,flag=True,time=time)
    operate_comment.append({"name": "二维码图片", "content": ser.qr})
    operate_comment.append({"name": "二维码归属", "content": ser.name})
    operate_comment.append({"name": "二维码标题", "content": ser.title})
    operate_comment.append({"name": "工作时间", "content": ser.time})
    log = Admin_operate_log(func="视频", up=1, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(ser)
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="添加成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="添加失败")

# 获取客服列表
@app.route('/pdd/admin/serlist', methods=["post", "get"])
@admin_require
def admin_ser_list(aid):
    status = request.args.get("status", type=inputs.boolean)
    page = request.args.get("page", default=1, type=int)
    keyword = request.args.get("keyword", type=str)
    pageSize = request.args.get('pageSize', default=10, type=int)
    sql = list()
    if status is not None:
        sql.append(Service.flag == status)
    if keyword:
        sql.append(or_(Service.title.like(f"%{keyword}%"),Service.name.like(f"%{keyword}%")))



    Count = db.session.query(Service.flag, db.func.count(Service.id).label("count"),
                                 ).group_by(Service.flag).all()
    Count = {i.flag: i.count for i in Count}

    ser = Service.query.filter(*sql).paginate(page, per_page=pageSize, error_out=False)
    data = []
    for i in ser.items:
        data.append({
            "id": i.id,
            "qrPath": API_SET.get("QINIU").get("qiniu_url") + i.qr,
            "qr": i.qr,
            "title": i.title,
            "name": i.name,
            "flag": i.flag,
            "time": i.time,
            "updateTime": str(i.updateTime),
        })
    return jsonify(code=0, msg="成功",
                   rows=data,
                   page=ser.page,
                   total=ser.total,
                   pages=ser.pages,
                   up=Count.get(True) if Count.get(True) else 0,
                   down=Count.get(False) if Count.get(False) else 0,
                   )

# 客服上线下线
@app.route('/pdd/admin/ser/updown', methods=["post", "get"])
@admin_require
def admin_ser_updown(aid):

    if not aid.job.imgText:
        return jsonify(code=-103,msg="权限不足")

    id = request.form.get("id", type=int)
    status = request.form.get("status", type=inputs.boolean)
    if id is None:
        return jsonify(code=-1, msg="请求出错")
    if status is None:
        return jsonify(code=-1,msg="请设置状态")

    ser = Service.query.get(id)
    if not ser:
        return jsonify(code=-1, msg="暂无该条记录，请刷新后重试")

    ser.flag = status
    try:
        operate_comment = []
        operate_comment.append({"name": "二维码归属", "content": ser.name})
        operate_comment.append({"name": "二维码标题", "content": ser.title})
        operate_comment.append(
            {"name": "操作", "content": "上线" if status else "下线"})
        log = Admin_operate_log(func="侧栏客服", up=4, comment=operate_comment, aid=aid.id)
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0,msg="修改成功",flag=ser.flag)
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败")

# 客服删除
@app.route('/pdd/admin/ser/delete', methods=["post", "get"])
@admin_require
def admin_ser_delete(aid):
    '''


    :param id:轮播id
    :param status:状态
    :return:
    '''
    if not aid.job.imgText:
        return jsonify(code=-103, msg="没有权限")
    id = request.form.get('id', default=0, type=int)
    if id is None:
        return jsonify(code=-1, msg="请求出错")

    ser = Service.query.get(id)
    if not ser:
        return jsonify(code=-1, msg="没后找到该条记录")

    operate_comment = []
    operate_comment.append({"name": "二维码", "content": ser.qr})
    operate_comment.append({"name": "二维码标题", "content": ser.title})
    log = Admin_operate_log(func="客服二维码", up=3, comment=operate_comment, aid=aid.id)

    try:
        QiniuDel(ser.qr)
        db.session.delete(ser)
        db.session.add(log)
        db.session.commit()

        return jsonify(code=0, msg="删除成功")
    except:
        db.session.rollback()

        return jsonify(code=-1, msg="删除失败")


# 编辑客服
@app.route('/pdd/admin/ser/edit', methods=["post"])
@admin_require
def admin_ser_edit(aid):
    '''
    :param id: 轮播id
    :param name: 轮播名称
    :param rank: 图片排序
    :param imgName:图片名称
    :param href:跳转链接
    :param zone:发布空间 1：首页 2：个人中心 3：功能页
    :return:
    '''
    if not aid.job.imgText:
        return jsonify(code=-103, msg="没有权限")
    id = request.form.get("id", type=int)
    qr = request.form.get("qr", type=str)
    title = request.form.get("title", type=str)
    name = request.form.get("name", type=str)
    time = request.form.get("time", type=str)

    if id is None:
        return jsonify(code=-1, msg="请求出错")
    # 添加日志
    operate_comment = []
    ser = Service.query.get(id)
    if not ser:
        return jsonify(code=-1, msg="没有找到该条记录")
    if name:
        operate_comment.append({"name": "二维码归属", "raw": ser.name, "content": name})
        ser.name = name
    if qr:
        operate_comment.append({"name": "二维码", "raw": ser.qr, "content": qr})
        ser.qr = qr
    if title:
        operate_comment.append({"name": "二维码标题", "raw": ser.title, "content": title})
        ser.title = title

    if time:
        operate_comment.append({"name": "工作时间", "raw": ser.time, "content": time})
        ser.time = time

    if len(operate_comment) >0:
        log = Admin_operate_log(func="轮播图", up=2, comment=operate_comment, aid=aid.id)
        db.session.add(log)
    try:
        db.session.commit()
        return jsonify(code=0, msg="修改成功",data={
            "id": ser.id,
            "qrPath": API_SET.get("QINIU").get("qiniu_url") + ser.qr,
            "qr": ser.qr,
            "title": ser.title,
            "name": ser.name,
            "flag": ser.flag,
            "time": ser.time,
            "updateTime": str(ser.updateTime),
        })
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败，服务器出错了，请稍后重试")

'''
会员管理

'''

# 获会员列表
@app.route('/pdd/admin/user/rank', methods=["post", "get"])
@admin_require
def admin_user_rank(aid):
    rank = UserRank.query.order_by(UserRank.level.asc(),UserRank.initial.asc()).all()

    data = [
        {
            "id":i.id,
            "name":i.name,
            "level":i.level,
            "color":i.color,
            "background":i.background,
            "price":round(i.price,2),
            "updateTime":str(i.updateTime),
            "initial":i.initial,
        } for i in rank
    ]

    return jsonify(code=0,msg="获取成功",data=data)

# 编辑会员
@app.route('/pdd/admin/user/rank/edit', methods=["post"])
@admin_require
def admin_user_rank_edit(aid):
    '''
    :param id: 轮播id
    :param name: 轮播名称
    :param rank: 图片排序
    :param imgName:图片名称
    :param href:跳转链接
    :param zone:发布空间 1：首页 2：个人中心 3：功能页
    :return:
    '''
    if not aid.job.price:
        return jsonify(code=-103, msg="没有权限")
    id = request.form.get("id", type=int)
    color = request.form.get("color", type=str)
    background = request.form.get("background", type=str)
    name = request.form.get("name", type=str)
    price = request.form.get("price", type=float)

    if id is None:
        return jsonify(code=-1, msg="请求出错")
    # 添加日志
    operate_comment = []
    rank = UserRank.query.get(id)
    if not rank:
        return jsonify(code=-1, msg="没有找到该条记录")
    if rank.initial:
        return jsonify(code=-1, msg="初始会员不能编辑修改")

    if name and rank.name !=name:
        operate_comment.append({"name": "会员名称", "raw": rank.name, "content": name})
        rank.name = name

    if color and rank.color !=color:
        operate_comment.append({"name": "字体颜色", "raw": rank.color, "content": color})
        rank.color = color

    if background and rank.background !=background:
        operate_comment.append({"name": "背景颜色", "raw": rank.background, "content": background})
        rank.background = background

    if price and rank.price !=price:
        operate_comment.append({"name": "价格", "raw": rank.price, "content": price})
        rank.price = price

    if len(operate_comment) >0:
        log = Admin_operate_log(func="会员等级", up=2, comment=operate_comment, aid=aid.id)
        db.session.add(log)
    try:
        db.session.commit()
        return jsonify(code=0, msg="修改成功",data={
            "id":rank.id,
            "name":rank.name,
            "level":rank.level,
            "color":rank.color,
            "background":rank.background,
            "price":round(rank.price,2),
            "updateTime":str(rank.updateTime),
            "initial":rank.initial,
        })
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败，服务器出错了，请稍后重试")

# 获会员功能列表
@app.route('/pdd/admin/user/rank/func', methods=["post", "get"])
@admin_require
def admin_user_rank_func(aid):
    rid = request.args.get("rid",type=int)
    if rid is None:
        return jsonify(code=-104,msg="没找到该条记录,404页面丢失")

    rank = UserRank.query.get(rid)
    if not rank:
        return jsonify(code=-104,msg="没找到该条记录,404页面丢失")
    data = [{
        "id":i.id,
        "name":i.func.name,
        "count":i.count,
        "updateTime":str(i.updateTime)
    } for i in rank.rf]

    return jsonify(code=0,msg="获取成功",data=data,funcName=rank.name)

# 添加会员功能
@app.route('/pdd/admin/user/rank/func/add', methods=["post", "get"])
@admin_require
def admin_user_rank_func_add(aid):
    if not aid.job.price:
        return jsonify(code=-103, msg="没有权限")

    rid = request.form.get("rid",type=int)
    fid = request.form.get("fid",type=int)
    count = request.form.get("count",type=int)
    if rid is None:
        return jsonify(code=-1,msg="会员id传入错误")
    if fid is None:
        return jsonify(code=-1, msg="请选择功能")
    if count is None:
        return jsonify(code=-1,meg="请填写使用次数")

    func = FuncData.query.get(fid)
    if not func:
        return jsonify(code=-1, msg="功能id出错，请刷新页面重试")

    rank = UserRank.query.get(rid)
    if not rank:
        return jsonify(code=-1,msg="会员id出错，请刷新页面重试")

    rf = RankFunc.query.filter(RankFunc.rid==rid,RankFunc.fid==fid).first()
    if rf:
        return jsonify(code=-1, msg="此会员下已有该条功能～")

    rf = RankFunc(fid=func.id,rid=rank.id,count=count)
    operate_comment = []
    operate_comment.append({"name": "功能名称", "content": func.name})
    operate_comment.append({"name": "会员名称", "content": rank.name})
    operate_comment.append({"name": "使用次数", "content": rf.count})
    log = Admin_operate_log(func="会员功能", up=1, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(rf)
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="添加成功", data={
                    "id":rf.id,
                    "name":rf.func.name,
                    "count":rf.count,
                    "updateTime":str(rf.updateTime)
                })
    except:
        db.session.rollback()
        return jsonify(code=-1,msg="添加失败")

# 编辑会员功能
@app.route('/pdd/admin/user/rank/func/edit', methods=["post"])
@admin_require
def admin_user_rank_func_edit(aid):
    '''
    :param id: 功能列表id
    :return:
    '''
    if not aid.job.price:
        return jsonify(code=-103, msg="没有权限")
    id = request.form.get("id", type=int)
    count = request.form.get("count", type=int)

    if id is None:
        return jsonify(code=-1, msg="请求出错")
    # 添加日志
    operate_comment = []
    rf = RankFunc.query.get(id)
    if not rf:
        return jsonify(code=-1, msg="没有找到该条记录")

    if count and rf.count != count:
        operate_comment.append({"name": "使用次数", "raw": rf.count, "content": count})
        rf.count = count

    if len(operate_comment) > 0:
        log = Admin_operate_log(func="会员:" + rf.urank.name, up=2, comment=operate_comment, aid=aid.id)
        db.session.add(log)
    try:
        db.session.commit()
        return jsonify(code=0, msg="修改成功", data={
            "id": rf.id,
            "name": rf.func.name,
            "count": rf.count,
            "updateTime": str(rf.updateTime)
        })
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败，服务器出错了，请稍后重试")

# 删除会员功能
@app.route('/pdd/admin/user/rank/func/delete', methods=["post"])
@admin_require
def admin_user_rank_func_delete(aid):
    '''
    :param id: 轮播id
    :param name: 轮播名称
    :param rank: 图片排序
    :param imgName:图片名称
    :param href:跳转链接
    :param zone:发布空间 1：首页 2：个人中心 3：功能页
    :return:
    '''
    if not aid.job.price:
        return jsonify(code=-103, msg="没有权限")
    id = request.form.get("id", type=int)

    if id is None:
        return jsonify(code=-1, msg="请求出错")
    # 添加日志
    rf = RankFunc.query.get(id)
    if not rf:
        return jsonify(code=-1, msg="没有找到该条记录")

    operate_comment = []
    operate_comment.append({"name": "功能名称", "content": rf.func.name})
    log = Admin_operate_log(func="会员:" + rf.urank.name +"使用功能", up=3, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(log)
        db.session.delete(rf)
        db.session.commit()
        return jsonify(code=0, msg="删除成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="删除失败，服务器出错了，请稍后重试")

# 获取功能列表
@app.route('/pdd/admin/func/group', methods=["GET"])
@admin_require
def admin_func_group(aid):
    '''
    :param id: 轮播id
    :param name: 轮播名称
    :param rank: 图片排序
    :param imgName:图片名称
    :param href:跳转链接
    :param zone:发布空间 1：首页 2：个人中心 3：功能页
    :return:
    '''

    func =FuncData.query.all()

    data = [{
        "fid":i.id,
        "name":i.name
    }for i in func]

    return jsonify(code=0,msg="获取成功",data=data)


# 获会员套餐列表
@app.route('/pdd/admin/user/rank/meal', methods=["post", "get"])
@admin_require
def admin_user_rank_meal(aid):
    rid = request.args.get("rid",type=int)
    if rid is None:
        return jsonify(code=-104,msg="没找到该条记录,404页面丢失")

    rank = UserRank.query.filter(UserRank.id==rid,UserRank.initial != True).first()
    if not rank:
        return jsonify(code=-104,msg="没找到该条记录,404页面丢失")

    data = [{
        "id":i.id,
        "name":i.name,
        "price":i.price,
        "days":i.days,
        "rateFlag":i.rateFlag,
        "rate":i.rate,
        "rateName":i.rateName,
        "sort":i.sort,
        "updateTime":str(i.updateTime)
    } for i in rank.meal]

    return jsonify(code=0,msg="获取成功",data=data,funcName=rank.name)

# 添加会员套餐
@app.route('/pdd/admin/user/rank/meal/add', methods=["post", "get"])
@admin_require
def admin_user_rank_meal_add(aid):
    if not aid.job.price:
        return jsonify(code=-103, msg="没有权限")

    rid = request.form.get("rid",type=int)
    days = request.form.get("days",type=int)
    price = request.form.get("price",type=float)
    name = request.form.get("name",type=str)
    rateFlag = request.form.get("rateFlag",type=inputs.boolean)
    rate = request.form.get("rate",type=float)
    rateName = request.form.get("rateName",type=str)
    sort = request.form.get("sort",type=int)




    if rid is None:
        return jsonify(code=-1,msg="会员id传入错误")
    if days is None:
        return jsonify(code=-1,meg="请填写使用天数")
    if price is None:
        return jsonify(code=-1, meg="请填写价格")
    if name is None:
        return jsonify(code=-1, meg="请填写套餐名")
    if sort is None:
        return jsonify(code=-1, meg="请填写排序")
    if rateFlag is None:
        return jsonify(code=-1, meg="请选择折扣开启或关闭")
    if rateFlag:
        if rate is None:
            return jsonify(code=-1, meg="折扣开启后请填写折扣")
        if rateName is None:
            return jsonify(code=-1, meg="折扣开启后请填写折扣名")

    rank = UserRank.query.get(rid)
    if not rank:
        return jsonify(code=-1, meg="没有找到此rid下的会员")
    if rank.initial:
        return jsonify(code=-1, meg="添加失败,此会员为初始会员")

    count = RankMeal.query.count()
    if count >= 6:
        return jsonify(code=-1, meg="添加失败,套餐数量只能添加6个")

    meal = RankMeal(rid=rank.id,name=name,price=price,rate=rate,rateName=rateName,rateFlag=rateFlag,days=days,sort=sort)

    operate_comment = []
    operate_comment.append({"name": "会员名称", "content": rank.name})
    operate_comment.append({"name": "套餐名称", "content": meal.name})
    operate_comment.append({"name": "价格", "content": meal.price})
    operate_comment.append({"name": "充值天数", "content": meal.days})
    operate_comment.append({"name": "折扣状态", "content": "开启" if meal.rateFlag else "关闭"})
    if meal.rateFlag:
        operate_comment.append({"name": "折扣", "content": meal.rate})
        operate_comment.append({"name": "折扣名称", "content": meal.rateName})

    log = Admin_operate_log(func="会员套餐", up=1, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(meal)
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="添加成功", data={
        "id":meal.id,
        "name":meal.name,
        "price":meal.price,
        "days":meal.days,
        "rateFlag":meal.rateFlag,
        "rate":meal.rate,
        "rateName":meal.rateName,
        "sort":meal.sort,
        "updateTime":str(meal.updateTime)
    })
    except:
        db.session.rollback()
        return jsonify(code=-1,msg="添加失败")


# 修改会员套餐
@app.route('/pdd/admin/user/rank/meal/edit', methods=["post", "get"])
@admin_require
def admin_user_rank_meal_edit(aid):
    if not aid.job.price:
        return jsonify(code=-103, msg="没有权限")
    id = request.form.get("id",type=int)
    days = request.form.get("days", type=int)
    price = request.form.get("price", type=float)
    name = request.form.get("name", type=str)
    rateFlag = request.form.get("rateFlag", type=inputs.boolean)
    rate = request.form.get("rate", type=float)
    rateName = request.form.get("rateName", type=str)
    sort = request.form.get("sort", type=int)
    if id is None:
        return jsonify(code=-1, msg="套餐id传入错误")

    if rateFlag:
        if rate is None:
            return jsonify(code=-1, meg="折扣开启后请填写折扣")
        if rateName is None:
            return jsonify(code=-1, meg="折扣开启后请填写折扣名称")


    meal = RankMeal.query.get(id)
    if not meal:
        return jsonify(code=-1, msg="没有找到该条记录，请刷新重试～")
    operate_comment =[]
    if days is not None and days != meal.days:
        operate_comment.append({"name": "充值天数", "raw": meal.days, "content": days})
        meal.days = days

    if price is not None and price != meal.price:
        operate_comment.append({"name": "使用价格", "raw": meal.price, "content": price})
        meal.price = price

    if name is not None and name != meal.name:
        operate_comment.append({"name": "套餐名称", "raw": meal.name, "content": name})
        meal.name = name

    if sort is not None and sort != meal.sort:
        operate_comment.append({"name": "排序", "raw": meal.sort, "content": sort})
        meal.sort = sort

    if rateFlag is not None:
        operate_comment.append({"name": "折扣状态", "raw": meal.rateFlag, "content": rateFlag})
        meal.rateFlag = rateFlag
        if meal.rateFlag:
            if rate is not None and rate != meal.rate:

                operate_comment.append({"name": "折扣", "raw": meal.rate, "content": rate})
                meal.rate = rate
            if rateName is not None and rateName != meal.rateName:
                operate_comment.append({"name": "折扣名称", "raw": meal.rateName, "content": rateName})
                meal.rateName = rateName
        else:
            operate_comment.append({"name": "折扣", "raw": meal.rate, "content": None})
            meal.rate = None
            operate_comment.append({"name": "折扣名称", "raw": meal.rateName, "content": None})
            meal.rateName = None



    if len(operate_comment) > 0:
        log = Admin_operate_log(func="会员"+meal.rank.name+"套餐", up=2, comment=operate_comment, aid=aid.id)
        db.session.add(log)

    try:
        db.session.commit()
        return jsonify(code=0, msg="修改成功", data={
            "id": meal.id,
            "name": meal.name,
            "price": meal.price,
            "days": meal.days,
            "rateFlag": meal.rateFlag,
            "rate": meal.rate,
            "rateName": meal.rateName,
            "sort": meal.sort,
            "updateTime": str(meal.updateTime)
        })
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败")



# 删除会员套餐
@app.route('/pdd/admin/user/rank/meal/delete', methods=["post"])
@admin_require
def admin_user_rank_meal_delete(aid):
    '''
    :param id: 轮播id
    :param name: 轮播名称
    :param rank: 图片排序
    :param imgName:图片名称
    :param href:跳转链接
    :param zone:发布空间 1：首页 2：个人中心 3：功能页
    :return:
    '''
    if not aid.job.price:
        return jsonify(code=-103, msg="没有权限")
    id = request.form.get("id", type=int)

    if id is None:
        return jsonify(code=-1, msg="请求出错")
    # 添加日志
    meal = RankMeal.query.get(id)
    if not meal:
        return jsonify(code=-1, msg="没有找到该条记录")

    operate_comment = []
    operate_comment.append({"name": "套餐名", "content": meal.name})
    log = Admin_operate_log(func="会员:" + meal.rank.name +"套餐", up=3, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(log)
        db.session.delete(meal)
        db.session.commit()
        return jsonify(code=0, msg="删除成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="删除失败，服务器出错了，请稍后重试")

'''
职位管理

'''

# 获会员职位列表
@app.route('/pdd/admin/job', methods=["post", "get"])
@admin_require
def admin_admin_job(aid):
    if not aid.job.account:
        return jsonify(code=-103,msg="您无权访问，需要管理员授权")

    job = Admin_job.query.order_by(Admin_job.initial.desc()).all()

    data = [
        {
            "id":i.id,
            "jobName":i.jobName,
            "func":i.func,
            "user":i.user,
            "imgText":i.imgText,
            "price":i.price,
            "allot":i.allot,
            "sell":i.sell,
            "Seo": i.Seo,
            "account": i.account,
            "updateTime":str(i.updateTime)

        } for i in job
    ]

    return jsonify(code=0,msg="获取成功",data=data)




# 创建新职位
@app.route('/pdd/admin/job/add', methods=["post", "get"])
@admin_require
def admin_admin_job_add(aid):
    if not aid.job.account:
        return jsonify(code=-103,msg="您无权创建，需要管理员授权")

    jobName = request.form.get("jobName",type=str)
    func = request.form.get("func",type=inputs.boolean)
    user = request.form.get("user", type=inputs.boolean)
    imgText = request.form.get("imgText", type=inputs.boolean)
    price = request.form.get("price", type=inputs.boolean)
    allot = request.form.get("allot", type=inputs.boolean)
    sell = request.form.get("sell", type=inputs.boolean)
    Seo = request.form.get("Seo", type=inputs.boolean)
    account = request.form.get("account", type=inputs.boolean)

    if jobName is None:
        return jsonify(code=-1,msg="请填写职位名称")
    if func is None:
        return jsonify(code=-1,msg="请选择功能权限")
    if user is None:
        return jsonify(code=-1,msg="请选择用户管理权限")
    if imgText is None:
        return jsonify(code=-1,msg="请选择图文管理权限")
    if price is None:
        return jsonify(code=-1,msg="请选择价格管理权限")
    if allot is None:
        return jsonify(code=-1,msg="请选择分配管理权限")
    if sell is None:
        return jsonify(code=-1,msg="请选择是否归属销售")
    if Seo is None:
        return jsonify(code=-1,msg="请选择SEO分析权限")
    if account is None:
        return jsonify(code=-1,msg="请选择职位管理权限")
    job = Admin_job(jobName=jobName,func=func,user=user,imgText=imgText,price=price,allot=allot,sell=sell,Seo=Seo,account=account,initial=False)
    operate_comment = []
    operate_comment.append({"name": "职位名称", "content": job.jobName})
    operate_comment.append({"name": "功能权限", "content": "开启" if job.func else "关闭"})
    operate_comment.append({"name": "用户权限", "content": "开启" if job.user else "关闭"})
    operate_comment.append({"name": "图文权限", "content":  "开启" if job.imgText else "关闭"})
    operate_comment.append({"name": "价格权限", "content": "开启" if job.price else "关闭"})
    operate_comment.append({"name": "分配权限", "content": "开启" if job.allot else "关闭"})
    operate_comment.append({"name": "是否销售", "content": "开启" if job.sell else "关闭"})
    operate_comment.append({"name": "SEO分析", "content": "开启" if job.Seo else "关闭"})
    operate_comment.append({"name": "职位管理", "content": "开启" if job.account else "关闭"})
    log = Admin_operate_log(func="会员套餐", up=1, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(job)
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="添加成功", data={
            "id":job.id,
            "jobName":job.jobName,
            "func":job.func,
            "user":job.user,
            "imgText":job.imgText,
            "price":job.price,
            "allot":job.allot,
            "sell":job.sell,
            "Seo": job.Seo,
            "account": job.account,
            "updateTime":str(job.updateTime)

        })
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="添加失败")



# 修改职位
@app.route('/pdd/admin/job/edit', methods=["post", "get"])
@admin_require
def admin_job_edit(aid):
    if not aid.job.account:
        return jsonify(code=-103, msg="您无权修改，需要管理员授权")

    id = request.form.get("id",type=int)
    jobName = request.form.get("jobName", type=str)
    func = request.form.get("func", type=inputs.boolean)
    user = request.form.get("user", type=inputs.boolean)
    imgText = request.form.get("imgText", type=inputs.boolean)
    price = request.form.get("price", type=inputs.boolean)
    allot = request.form.get("allot", type=inputs.boolean)
    sell = request.form.get("sell", type=inputs.boolean)
    Seo = request.form.get("Seo", type=inputs.boolean)
    account = request.form.get("account", type=inputs.boolean)

    if id is None:
        return jsonify(code=-1, msg="套餐id传入错误")

    job = Admin_job.query.get(id)
    if not job:
        return jsonify(code=-1, msg="没有找到该条记录，请刷新重试～")
    if job.initial:
        return jsonify(code=-1, msg="初始职位不能进行修改～")

    operate_comment =[]
    if jobName is not None and jobName != job.jobName:
        operate_comment.append({"name": "职位名称", "raw": job.jobName, "content": jobName})
        job.jobName = jobName

    if func is not None and func != job.func:
        operate_comment.append({"name": "功能权限", "raw": job.func, "content": func})
        job.func = func

    if user is not None and user != job.user:
        operate_comment.append({"name": "用户权限", "raw": job.user, "content": user})
        job.user = user

    if imgText is not None and imgText != job.imgText:
        operate_comment.append({"name": "图文权限", "raw": job.imgText, "content": imgText})
        job.imgText = imgText

    if price is not None and price != job.price:
        operate_comment.append({"name": "价格权限", "raw": job.price, "content": price})
        job.price = price

    if allot is not None and allot != job.allot:
        operate_comment.append({"name": "分配权限", "raw": job.allot, "content": allot})
        job.allot = allot

    if sell is not None and sell != job.sell:
        operate_comment.append({"name": "是否销售", "raw": job.sell, "content": sell})
        job.sell = sell

    if Seo is not None and Seo != job.Seo:
        operate_comment.append({"name": "SEO分析", "raw": job.Seo, "content": Seo})
        job.Seo = Seo

    if account is not None and account != job.account:
        operate_comment.append({"name": "职位管理", "raw": job.account, "content": account})
        job.account = account


    if len(operate_comment) > 0:
        log = Admin_operate_log(func="职位", up=2, comment=operate_comment, aid=aid.id)
        db.session.add(log)

    try:
        db.session.commit()
        return jsonify(code=0, msg="修改成功", data={
            "id":job.id,
            "jobName":job.jobName,
            "func":job.func,
            "user":job.user,
            "imgText":job.imgText,
            "price":job.price,
            "allot":job.allot,
            "sell":job.sell,
            "Seo": job.Seo,
            "account": job.account,
            "updateTime":str(job.updateTime)

        })
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败")



# 删除职位
@app.route('/pdd/admin/job/delete', methods=["post"])
@admin_require
def admin_job_delete(aid):
    '''
    :param id: 轮播id
    :param name: 轮播名称
    :param rank: 图片排序
    :param imgName:图片名称
    :param href:跳转链接
    :param zone:发布空间 1：首页 2：个人中心 3：功能页
    :return:
    '''
    if not aid.job.account:
        return jsonify(code=-103, msg="您无权删除，需要管理员授权～")
    id = request.form.get("id", type=int)

    if id is None:
        return jsonify(code=-1, msg="请求出错")
    # 添加日志
    job = Admin_job.query.get(id)
    if not job:
        return jsonify(code=-1, msg="没有找到该条记录")
    if job.initial:
        return jsonify(code=-1, msg="初始职位不能删除")

    admin = db.session.query(db.func.count(Admin.id).label("sum")).filter(Admin.jid == job.id).first()

    if admin.sum >0:
        return jsonify(code=-1, msg="该职位下面还有账号，不能删除")

    operate_comment = []
    operate_comment.append({"name": "职位名称", "content": job.jobName})
    log = Admin_operate_log(func="职位", up=3, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(log)
        db.session.delete(job)
        db.session.commit()
        return jsonify(code=0, msg="删除成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="删除失败，服务器出错了，请稍后重试")


'''
账号管理
'''

# 获会员职位列表盒子
@app.route('/pdd/admin/job/box', methods=["post", "get"])
@admin_require
def admin_admin_job_box(aid):
    if not aid.job.account:
        return jsonify(code=-103,msg="您无权访问，需要管理员授权")

    job = Admin_job.query.order_by(Admin_job.initial.desc()).all()

    data = [
        {
            "id":i.id,
            "jobName":i.jobName,
        } for i in job
    ]

    return jsonify(code=0,msg="获取成功",data=data)


# 获取后台账号列表
@app.route('/pdd/admin/account', methods=["post", "get"])
@admin_require
def admin_account(aid):
    '''
    :param status:上下线
    :return:
    '''
    if not aid.job.account:
        jsonify(code=-103,msg="您无权访问，需要管理员授权")
    jobId = request.args.get("jobId", type=int)
    status = request.args.get("status", type=inputs.boolean)
    page = request.args.get("page", default=1, type=int)
    keyword = request.args.get("keyword", type=str)
    pageSize = request.args.get('pageSize', default=10, type=int)
    sql = list()
    if status is not None:
        sql.append(Admin.flag == status)
    if jobId:
        sql.append(Admin.jid == jobId)
    if keyword:
        sql.append(or_(Admin.username.like(f"%{keyword}%"),
                       Admin.name.like(f"%{keyword}%"),
                       Admin.phone.like(f"%{keyword}%")))

    adminCount = db.session.query(Admin.flag, db.func.count(Admin.id).label("count"),
                                 ).group_by(
        Admin.flag).all()
    adminCount = {i.flag: i.count for i in adminCount}
    admin = Admin.query.filter(*sql).paginate(page, per_page=pageSize, error_out=False)
    data = []
    for i in admin.items:
        data.append({
            "id": i.id,
            "username": i.username,
            "userPhoto": API_SET.get("QINIU").get("qiniu_url") + i.userPhoto if i.userPhoto else None,
            "phone": i.phone,
            "wechat": i.wechat,
            "name": i.name,
            "sex": i.sex,
            "address": i.address,
            "job": i.job.jobName if i.jid is not None else "暂无职位",
            "createtime": str(i.createtime),
            "birthdate":str(i.birthdate),
            "jobId": i.job.id if i.jid is not None else 0,
            "flag":i.flag,
        })
    return jsonify(code=0, msg="成功",
                   rows=data,
                   page=admin.page,
                   total=admin.total,
                   pages=admin.pages,
                   up=adminCount.get(True) if adminCount.get(True) else 0,
                   down=adminCount.get(False) if adminCount.get(False) else 0,
                   )


# 创建新账号
@app.route('/pdd/admin/account/add', methods=["post", "get"])
@admin_require
def admin_admin_account_add(aid):
    if not aid.job.account:
        return jsonify(code=-103,msg="您无权创建，需要管理员授权")

    username = request.form.get("username",type=str)
    password = request.form.get("password",type=str)
    name = request.form.get("name", type=str)
    sex = request.form.get("sex", type=inputs.boolean)
    jobId = request.form.get("jobId", type=int)
    birthdate = request.form.get("birthdate", type=str)
    address = request.form.get("address", type=str)
    phone = request.form.get("phone", type=str)
    wechat = request.form.get("wechat", type=str)



    if username is None:
        return jsonify(code=-1,msg="请填写用户名")

    admin = Admin.query.filter(Admin.username==username).first()
    if admin:
        return jsonify(code=-1, msg="已有该账号")

    if password is None:
        return jsonify(code=-1,msg="请填写密码")
    v = passWord(password, 25, 8)

    if v == 2:
        return jsonify(code=-1, msg="密码不能低于8位")
    if v == 3:
        return jsonify(code=-1, msg="密码长度高于25位")
    if v == 4:
        return jsonify(code=-1, msg="请输入的密码为数字字母加字符的任意组合")

    if sex is None:
        return jsonify(code=-1,msg="请选择性别")
    if jobId is None:
        return jsonify(code=-1,msg="请选择职位")
    if birthdate is None:
        return jsonify(code=-1,msg="请选择生日")
    if name is None:
        return jsonify(code=-1,msg="请填写姓名")
    job = Admin_job.query.get(jobId)
    if not job:
        return jsonify(code=-1,msg="未找到该职位，请刷新重试")


    admin = Admin(username=username,password=password,userPhoto=None,phone=phone,name=name,nick=None,
                  sex=sex,address=address,wechat=wechat,birthdate=birthdate,flag=True,jid=job.id)
    operate_comment = []
    operate_comment.append({"name": "用户名", "content": admin.username})
    operate_comment.append({"name": "姓名", "content": admin.name})
    operate_comment.append({"name": "联系电话", "content": admin.phone})
    operate_comment.append({"name": "性别", "content": "男" if admin.sex else "女"})
    operate_comment.append({"name": "职位", "content": job.jobName})
    log = Admin_operate_log(func="后台账号", up=1, comment=operate_comment, aid=aid.id)
    try:
        db.session.add(admin)
        db.session.add(log)
        db.session.commit()
        return jsonify(code=0, msg="添加成功", data={
            "id": admin.id,
            "username": admin.username,
            "userPhoto": API_SET.get("QINIU").get("qiniu_url") + admin.userPhoto if admin.userPhoto else None,
            "phone": admin.phone,
            "wechat": admin.wechat,
            "name": admin.name,
            "sex": admin.sex,
            "address": admin.address,
            "job": admin.job.jobName if admin.jid is not None else "暂无职位",
            "jobId":admin.job.id if admin.jid is not None else 0,
            "createtime": str(admin.createtime),
            "birthdate": str(admin.birthdate),
            "flag": admin.flag,
        })
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="添加失败")

# 修改账号
@app.route('/pdd/admin/account/edit', methods=["post", "get"])
@admin_require
def admin_account_edit(aid):
    if not aid.job.account:
        return jsonify(code=-103, msg="您无权修改，需要管理员授权")

    id = request.form.get("id",type=int)
    password = request.form.get("password", type=str)
    name = request.form.get("name", type=str)
    sex = request.form.get("sex", type=inputs.boolean)
    jobId = request.form.get("jobId", type=int)
    birthdate = request.form.get("birthdate", type=str)
    address = request.form.get("address", type=str)
    phone = request.form.get("phone", type=str)
    wechat = request.form.get("wechat", type=str)

    if id is None:
        return jsonify(code=-1, msg="账号id传入错误")
    admin = Admin.query.get(id)


    if not admin:
        return jsonify(code=-1, msg="没有找到该账号，请刷新重试～")

    if admin.initial and admin.username != aid.username:

        return jsonify(code=-1, msg="该账号为初始账号只有自己能编辑")

    operate_comment = []
    if jobId:
        job = Admin_job.query.get(jobId)
        if not job:
            return jsonify(code=-1, msg="没有找到该职位，请刷新重试～")

        operate_comment.append({"name": "职位", "raw": admin.job.jobName if admin.jid is not None else "暂无职位", "content": job.jobName})
        admin.jid = job.id

    if password is not None and password != admin.password:
        operate_comment.append({"name": "密码", "raw": "***********", "content": "***********"})
        admin.password = password

    if name is not None and name != admin.name:
        operate_comment.append({"name": "姓名", "raw": admin.name, "content": name})
        admin.name = name

    if sex is not None and sex != admin.sex:
        operate_comment.append({"name": "性别", "raw": "男" if admin.sex else "女", "content": "男" if sex else "女"})
        admin.sex = sex

    if birthdate is not None and birthdate != str(admin.birthdate):
        operate_comment.append({"name": "生日", "raw": str(admin.birthdate), "content": birthdate})
        admin.birthdate = birthdate

    if address is not None and address != admin.address:
        operate_comment.append({"name": "住址", "raw": admin.address, "content": address})
        admin.address = address

    if phone is not None and phone != admin.phone:
        operate_comment.append({"name": "联系电话", "raw": admin.phone, "content": phone})
        admin.phone = admin

    if wechat is not None and wechat != admin.wechat:
        operate_comment.append({"name": "微信", "raw": admin.wechat, "content": wechat})
        admin.wechat = wechat

    if len(operate_comment) > 0:
        log = Admin_operate_log(func="后台账号", up=2, comment=operate_comment, aid=aid.id)
        db.session.add(log)

    try:
        db.session.commit()
        return jsonify(code=0, msg="修改成功", data={
            "id": admin.id,
            "username": admin.username,
            "userPhoto": API_SET.get("QINIU").get("qiniu_url") + admin.userPhoto if admin.userPhoto else None,
            "phone": admin.phone,
            "wechat": admin.wechat,
            "name": admin.name,
            "sex": admin.sex,
            "address": admin.address,
            "job": admin.job.jobName if admin.jid is not None else "暂无职位",
            "createtime": str(admin.createtime),
            "birthdate": str(admin.birthdate),
            "flag": admin.flag,
            "jobId": admin.job.id if admin.jid is not None else 0,
        })
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败")


# 删除账号
@app.route('/pdd/admin/account/delete', methods=["post"])
@admin_require
def admin_account_delete(aid):
    '''
    :param id: 轮播id
    :param name: 轮播名称
    :param rank: 图片排序
    :param imgName:图片名称
    :param href:跳转链接
    :param zone:发布空间 1：首页 2：个人中心 3：功能页
    :return:
    '''
    if not aid.job.account:
        return jsonify(code=-103, msg="您无权删除，需要管理员授权～")
    id = request.form.get("id", type=int)

    if id is None:
        return jsonify(code=-1, msg="请求出错")
    # 添加日志
    admin = Admin.query.get(id)

    if not admin:
        return jsonify(code=-1, msg="没有找到该条记录")


    if admin.initial:
        return jsonify(code=-1, msg="该账号为初始账号无法删除")

    operate_comment = []
    operate_comment.append({"name": "用户名", "content": admin.username})
    operate_comment.append({"name": "姓名", "content": admin.name})
    log = Admin_operate_log(func="后台账号", up=3, comment=operate_comment, aid=aid.id)
    if admin.userPhoto:
        QiniuDel(admin.userPhoto)

    try:
        db.session.add(log)
        db.session.delete(admin)
        db.session.commit()
        return jsonify(code=0, msg="删除成功")
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="删除失败，服务器出错了，请稍后重试")


# 修改账号状态
@app.route('/pdd/admin/account/status', methods=["post", "get"])
@admin_require
def admin_account_status(aid):
    if not aid.job.account:
        return jsonify(code=-103, msg="您无权修改，需要管理员授权")

    id = request.form.get("id",type=int)
    status = request.form.get("status", type=inputs.boolean)


    if id is None:
        return jsonify(code=-1, msg="账号id传入错误")
    admin = Admin.query.get(id)
    if not admin:
        return jsonify(code=-1, msg="没有找到该账号，请刷新重试～")
    if admin.initial:
        return jsonify(code=-1, msg="该账号为初始账号无法停用")

    operate_comment = []
    if status is not None and status != admin.flag:
        operate_comment.append({"name": "状态", "raw": "正常" if admin.flag else "停用", "content": "正常" if status else "停用"})
        admin.flag = status

    if len(operate_comment) > 0:
        log = Admin_operate_log(func="后台账号"+admin.username, up=2, comment=operate_comment, aid=aid.id)
        db.session.add(log)

    try:
        db.session.commit()
        return jsonify(code=0, msg="修改成功", flag=admin.flag)
    except:
        db.session.rollback()
        return jsonify(code=-1, msg="修改失败")